import os
from importlib import import_module
from datetime import datetime, timedelta
import time
import random
import string
import requests
from urllib3.exceptions import InsecureRequestWarning
from playwright.sync_api import sync_playwright
import re

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

sso = import_module("sso_auth")
path = os.path
sn = import_module("switch_network")
printer = import_module("printer").IndentPrinter(indent=1)
auth_info = None
data_path = os.environ["DATA_PATH"]

session = requests.session()

headers = {
    "Accept": "image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, */*",
    "User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; Tablet PC 2.0)",
}
urlencode_headers = headers.copy()
urlencode_headers["Content-Type"] = "application/x-www-form-urlencoded"

a_href_pattern = r'a href="([^"]+)"'


def download_jkyy(session, now, today, p_day):
    # 获取家宽运营系统入口地址
    zyyw_res = session.get(
        "http://eomswf.gmcc.net/default/com.huawei.nsm.platform.newpf.prIndex.flow",
        verify=False,
        headers=headers,
    )
    match_zyyw = re.search(a_href_pattern, zyyw_res.text)
    if not match_zyyw:
        printer("未找到家宽运营主页跳转地址,中止任务")
    zyyw_res = session.get(match_zyyw.group(1), headers=headers, verify=False)
    # with open("t_html/4_zyyw.html", "w", encoding="utf-8") as file:
    #     file.write(zyyw_res.text)

    # 进入家宽运营系统入
    jk_url = "http://eomswf.gmcc.net/default/zyyw/jkwh/index.jsp?userOrg=%25E9%2593%2581%25E9%2580%259A-%25E8%258C%2582%25E5%2590%258D-%25E5%25AE%25B6%25E5%25AE%25A2%25E8%25A3%2585%25E7%25BB%25B4-%25E8%258C%2582%25E5%258D%2597%25E5%258C%25BA%25E5%259F%259F%25E4%25B8%25AD%25E5%25BF%2583-%25E8%25B4%25A8%25E6%258E%25A7%25E7%25BB%2584-%25E5%2590%25B4%25E8%25A3%2595%25E8%25AF%2597&user_city=MM"
    jk_res = session.get(jk_url, headers=headers, verify=False)

    # with open("t_html/6_jk.html", "w", encoding="utf-8") as file:
    #     file.write(jk_res.text)

    download_list = [
        (
            16,
            "在途工单统计",
            {
                "medthType": "ZTGDCOMMDown",
                "startDate": f"2025-02-10 00:00:00",
                "endDate": today,
                "city": "MM",
                "gdly": "all",
                "ywfl": "all",
                "kdlx": "ALL",
                "swkddy": 1,
                "dysx": "all",
                "qydk": "all",
                "pdxt": "all",
                "vipl": "all",
            },
        ),
        (
            35,
            "投诉处理效率统计(新)",
            {
                "medthType": "TSXLRateNewCOMMDown",
                "startDate": p_day,
                "endDate": today,
                "city": "%E8%8C%82%E5%90%8D",
                "gdly": "all",
                "ywfl": "all",
                "kdlx": "ALL",
                "swkddy": 1,
                "dysx": "all",
                "qydk": "all",
                "tssource": "all",
                "pdxt": "all",
                "vipl": "all",
                "ywflSub": "all",
            },
        ),
        (
            22,
            "设备更换统计",
            {
                "medthType": "SBGHCOMMDown",
                "startDate": p_day,
                "endDate": today,
                "city": "MM",
            },
        ),
    ]

    for jid, name, create_payload in download_list:

        dt = now.strftime("%a %b %d %H:%M:%S ") + "UTC+0800 " + now.strftime("%Y")
        xml_data = f"""<?xml version="1.0" encoding="utf-8"?>
          <root>
              <params>
                  <param>
                      <key>kpi/JID</key>
                      <value>{jid}</value>
                  </param>
              </params>
              <data></data>
          </root>"""

        to_page_payload = {"__ajaxParam": xml_data}

        to_page_res = session.post(
            "http://eomswf.gmcc.net/default/zyyw/jkwh/com.huawei.nsm.jkwh.getData.getKpiUrl.biz.ajax?time="
            + dt,
            data=to_page_payload,
            headers=urlencode_headers,
            verify=False,
        )
        pattern_toPage = r"\>([^\"]+)\<\/url\>"
        match_toPage = re.search(pattern_toPage, to_page_res.text)
        if not match_toPage:
            printer(f"未找到【{name}】入口地址,中止任务")
            return

        # with open("t_html/7_to_jk.html", "w", encoding="utf-8") as file:
        #     file.write(to_page_res.text)

        _u = match_toPage.group(1).replace("amp;", "")
        page_res = session.get(_u + "&user_city=MM", headers=headers, verify=False)

        # with open(f"t_html/{name}.html", "w", encoding="utf-8") as file:
        #     file.write(page_res.text)

        match_page = re.search(a_href_pattern, page_res.text)
        if match_page:
            printer(f"需跳转【{name}】")
            join_page_res = session.get(
                match_page.group(1), headers=headers, verify=False
            )
        elif page_res.text.find(name) >= 0:
            printer(f"无需跳转【{name}】")
        else:
            printer(f"打开【{name}】页失败")
            continue

        create_file_url = "http://emipserver4.gmcc.net/kpiframe/downLoad.do"

        create_file_res = session.post(
            create_file_url,
            headers=urlencode_headers,
            data=create_payload,
            verify=False,
        )
        printer(create_file_res.text)

        download_res = session.get(
            "http://emipserver4.gmcc.net/kpiframe/subject/tscl2/xlsfileDownload.jsp?filePath="
            + create_file_res.text,
            verify=False,
            headers=headers,
        )
        if download_res.status_code == 200:
            file_path = path.join(data_path, r"eoms系统", name + ".csv")

            with open(file_path, "wb") as f:
                f.write(download_res.content)
            printer(f"文件下载完成: {file_path}")


def download_xngd(session, now, today, p_day):
    printer("开始导出T-1手工批量派单归档工单")
    gxhgd_res = session.get(
        "http://eomswf.gmcc.net/default/com.huawei.nsm.platform.query.ticketQuery.flow?code=TSCL_GZ_QUERY&params/fieldCfgsProcess=FieldCfgsProcess4Wf&params/processID=29&params/isSaveProcessID4Label=Y&params/labelCfgProcess=LabelCfgProcess4Wf",
        verify=False,
        headers=urlencode_headers,
    )
    gxhgd_match = re.search(a_href_pattern, gxhgd_res.text)
    if gxhgd_match:
        gxhgd_res = session.get(
            gxhgd_match.group(1),
            verify=False,
            headers=urlencode_headers,
        )
        # with open("t_html/ganzhi.html", "w", encoding="utf-8") as file:
        #     file.write(gxhgd_res.text)

    f_name1 = f"T-1手工批量派单归档工单{''.join(random.choices(string.digits, k=6))}"
    his_order_payload = {
        "query/unique": "+_qf_maetnvdve6xzr",
        "query/queryByParticipantView": "N",
        "query/isSetCSStyle": "Y",
        "query/supportSetPageSize": "Y",
        "query/submitFieldValueMap/BIZ_ENDTIME": "[object Object]",
        "query/queryPageSize": "20",
        "query/type": "commoncx",
        "query/submitFieldValueMap/TICKETFLAG": "0",
        "query/submitFieldValueMap/BUSINESSCITY": "茂名分公司",
        "query/queryEntityType": "ticket",
        "query/changeQView": "Y",
        "query/processId": "29",
        "query/pageCode": "TSCL_GZ_QUERY",
        "query/queryByOfflineView": "Y",
        "query/submitFieldIDs": "PROCESSID,TICKETFLAG,BUSINESSCITY,TICKETTYPE,BIZ_ENDTIME",
        "query/processNotCompletedStatus": "N",
        "query/processID": "29",
        "query/submitFieldValueMap/PROCESSID": "29",
        "query/submitFieldValueMap/TICKETTYPE": "手工批量派单",
        "query/queryIntervalCfg": "-1",
        "criteria/_expr[2]/TICKETFLAG": "0",
        "criteria/_or[1]/_expr[1]/TICKETTYPE": "手工批量派单",
        "criteria/_expr[4]/_max": today,
        "criteria/_expr[4]/_property": "BIZ_ENDTIME",
        "criteria/_expr[1]/PROCESSID": "29",
        "criteria/_expr[4]/_min": p_day,
        "criteria/_expr[4]/_op": "between",
        "criteria/_entity": "com.huawei.nsm.common.common.TBL_COMM_COMMONTICKET",
        "criteria/_expr[3]/BUSINESSCITY": "茂名分公司",
        "templateName": "queryplateform/tsclcommonquerydaochu.csv",
        "extParams/exportAll": "Y",
        "extParams/exportAllFileName": f_name1,
        "extParams/exportAllFileDesc": "",
    }
    c_his_res = session.post(
        "http://eomswf.gmcc.net/default/com.huawei.nsm.platform.query.ticketExport.flow",
        headers=urlencode_headers,
        verify=False,
        data=his_order_payload,
    )

    if c_his_res.status_code == 200 and c_his_res.text.find("按钮查看导出文件") > 0:
        printer(f"【{f_name1}】文件创建下载任务成功")
    else:
        printer(f"【{f_name1}】文件创建下载任务失败")

    # 下载性能工单数据

    printer("开始导出在途和归档性能工单")
    xngd_res = session.get(
        "http://eomswf.gmcc.net/default/com.huawei.nsm.platform.query.ticketQuery.flow?code=COMM_TICKET_QUERY&params/fieldCfgsProcess=FieldCfgsProcess4Wf&params/processID=2020&params/isSaveProcessID4Label=Y&params/labelCfgProcess=LabelCfgProcess4Wf",
        verify=False,
        headers=urlencode_headers,
    )
    xngd_match = re.search(a_href_pattern, xngd_res.text)
    if xngd_match:
        xngd_res = session.get(
            xngd_match.group(1),
            verify=False,
            headers=urlencode_headers,
        )
    if now.month == 1:
        # 如果当前是1月，则上个月是去年的12月
        last_month_first_day = datetime(now.year - 1, 12, 1).strftime(
            "%Y-%m-%d 00:00:00"
        )
    else:
        # 否则，直接将月份减1
        last_month_first_day = datetime(now.year, now.month - 1, 1).strftime(
            "%Y-%m-%d 00:00:00"
        )
    startDate = (
        now.strftime("%Y-%m-01 00:00:00") if now.day > 8 else last_month_first_day
    )
    endtDate = now.strftime("%Y-%m-%d 00:00:00")
    f_name2 = f"在途性能工单{''.join(random.choices(string.digits, k=6))}"
    f_name3 = f"归档性能工单{''.join(random.choices(string.digits, k=6))}"
    xngd_p = [
        ("+_qf_maf6053915uden", "N", f_name2),
        ("+_qf_maf64ouw14izst", "Y", f_name3),
    ]

    for unique, offine, f_name in xngd_p:

        xngd_payload = {
            "query/unique": unique,
            "query/submitFieldValueMap/FAULTDEALCITY": "茂名",
            "query/submitFieldValueMap/CREATETIME": "[object Object]",
            "query/queryByParticipantView": "N",
            "query/isSetCSStyle": "Y",
            "query/supportSetPageSize": "Y",
            "query/queryPageSize": "20",
            "query/type": "commoncx",
            "query/submitFieldValueMap/TICKETFLAG": "0",
            "query/queryEntityType": "ticket",
            "query/changeQView": "Y",
            "query/processId": "2020",
            "query/pageCode": "COMM_TICKET_QUERY",
            "query/queryParticipantCreateTimeCondition": f"{startDate};{endtDate}",
            "query/queryByOfflineView": offine,
            "query/submitFieldIDs": "PROCESSID,CREATETIME,TICKETFLAG,FAULTDEALCITY",
            "query/processNotCompletedStatus": "N",
            "query/processID": "2020",
            "query/submitFieldValueMap/PROCESSID": "2020",
            "query/queryIntervalCfg": "-1",
            "criteria/_expr[1]/PROCESSID": "2020",
            "criteria/_expr[3]/TICKETFLAG": "0",
            "criteria/_expr[2]/_property": "CREATETIME",
            "criteria/_expr[4]/FAULTDEALCITY": "茂名",
            "criteria/_entity": "com.huawei.nsm.common.common.TBL_COMM_COMMONTICKET",
            "criteria/_expr[2]/_max": endtDate,
            "criteria/_expr[2]/_min": startDate,
            "criteria/_expr[2]/_op": "between",
            "templateName": "queryplateform/性能管理个性化查询导出模板.csv",
            "extParams/exportAll": "Y",
            "extParams/qViewId": "63",
            "extParams/exportAllFileName": f_name,
            "extParams/exportAllFileDesc": "",
        }

        c_xngd_res = session.post(
            "http://eomswf.gmcc.net/default/com.huawei.nsm.platform.query.ticketExport.flow",
            headers=urlencode_headers,
            verify=False,
            data=xngd_payload,
        )
        if (
            c_xngd_res.status_code == 200
            and c_xngd_res.text.find("按钮查看导出文件") > 0
        ):
            printer(f"【{f_name}】文件创建下载任务成功")
        else:
            printer(f"【{f_name}】文件创建下载任务失败")

    printer("等待文件创建中...")
    check_task_payload = {
        "pageCond/begin": 0,
        "pageCond/length": 10,
        "pageCond/isCount": "true",
    }

    f_names = [f"{f_name1}.csv", f"{f_name2}.csv", f"{f_name3}.csv"]
    while True:
        his_task_res = session.post(
            "http://eomswf.gmcc.net/default/com.huawei.nsm.platform.query.queryPersonTicketExport.flow",
            verify=False,
            headers=urlencode_headers,
            data=check_task_payload,
        )
        if his_task_res.status_code != 200:
            printer("查询导出状态异常")
        json = his_task_res.json()
        rlist = json["result"]
        mytask_list = [
            (item["ID"], item["DISPLAYNAME"])
            for item in rlist
            if item["DISPLAYNAME"] in f_names
        ]
        printer("已生成文件:", mytask_list)
        if len(mytask_list) == len(f_names):
            break
        time.sleep(5)

    printer("待下载列表：")
    printer(mytask_list)
    if not len(mytask_list):
        return

    for ID, NAME in mytask_list:
        NAME = NAME[:-10] + ".csv"
        local_csv_path = path.join(data_path, r"eoms系统", NAME)

        if os.path.exists(local_csv_path):
            printer(f"[下载文件] {NAME} CSV 文件已存在，删除旧文件：{local_csv_path}")
            os.remove(local_csv_path)

        res = session.get(
            f"http://eomswf.gmcc.net/default/com.huawei.nsm.platform.query.ticketExport.flow?_eosFlowAction=exportFileDownload&fileId={ID}"
        )

        if res.status_code == 200:
            try:
                with open(local_csv_path, "wb") as f:
                    f.write(res.content)

            except Exception as e:
                printer(f"[下载文件] {NAME} 失败，发生错误：{e}")
                raise e
        else:
            printer(f"[下载文件] {NAME} 请求失败，状态码：{res.status_code}")
            printer("Response Content:", res.text)
            raise ValueError("下载文件请求失败")


def main():
    global auth_info

    if sn.wait_for_system("temip.gmcc.net"):

        now = datetime.now()
        today = now.strftime("%Y-%m-%d 00:00:00")
        p_day = (now - timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")

        printer("EOMS已可访问")
        printer("[下载数据] 开始")
        printer.add(1)
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=False)
            page = browser.new_page()
            auth_url = sso.login(
                browser=page,
                client_id="emip_gmcc_net",
                return_url="https://temip.gmcc.net:443/cas/login?service=http://www.emip.gmcc.net/Portal2/index.jsp",
                playwright=True,
            )
        

        h1 = headers.copy()
        h1["Referer"] = auth_url
        res1 = session.get(auth_url, headers=h1, verify=False)

        # with open("t_html/1_.html", "w", encoding="utf-8") as file:
        #     file.write(res1.text)
        action_pattern = r'action="([^"]+)"'
        action_match = re.search(action_pattern, res1.text)
        if not action_match:
            printer("未找到1.eoms登录表单提交地址,中止任务")

        lt_pattern = r'"lt" value="([^"]+)"'
        lt_match = re.search(lt_pattern, res1.text)
        if not lt_match:
            printer("未找到1.eoms登录表单所需参数【lt】")

        data = {
            "captcha_response": "x0OTiSSwGHoZiJburK7Q",
            "login_type": "osso",
            "username": "dwwuyushi",
            "password": "Gmcc2025**##",
            "lt": lt_match.group(1),
            "_eventId": "submit",
            "j_captcha_response": "",
        }
        res2 = session.post(
            "https://temip.gmcc.net:443/" + action_match.group(1),
            headers=urlencode_headers,
            data=data,
            verify=False,
        )

        match3 = re.search(a_href_pattern, res2.text)
        if not match3:
            printer("未找到eoms主页跳转地址,中止任务")

        session.get(match3.group(1), verify=False, headers=headers)

        #  进入 res3就说明已经登录成功
        printer("进入成功主页成功")
        # 下载家宽运营系统三分表
        download_jkyy(session, now, today, p_day)

        # 下载性能工单两份和T-1手工派单
        download_xngd(session, now, today, p_day)

    else:
        # time.sleep(120)
        printer("连接OA网失败")
    printer("[下载数据] 👏 完成，总耗时<run_time>。", run_time="hh:mm:ss")

    # sn.connect_to_internet()


if __name__ == "__main__":
    main()
